package v1_httpserver

import (
	"net/http"
)

var _ Server = &HttpServer{}

type HandleFunc func(ctx Context)

type Server interface {
	http.Handler
	Start(addr string) error
	// AddRoute 用于路由注册
	AddRoute(method string, path string, handleFunc HandleFunc) // 核心接口尽量少定义方法，衍生方法定义在实现上
}

type HttpServer struct {
}

// ServeHTTP 处理请求的入口
func (h *HttpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	// 请求一来先构造 处理本次请求的 context
	ctx := &Context{
		Req:  request,
		Resp: writer,
	}
	// 开始处理请求
	h.server(ctx)
}

func (h *HttpServer) Start(addr string) error {
	return http.ListenAndServe(addr, h)
	// 也可以自己创建 server
	//l, err := net.Listen("tcp", addr)
	//if err != nil {
	//	return err
	//}
	//return http.Serve(l, h)
}

func (h *HttpServer) AddRoute(method string, path string, handleFunc HandleFunc) {
	//TODO implement me
	panic("implement me")
}

func (h *HttpServer) Get(path string, handleFunc HandleFunc) { // addRoute 的衍生方法
	h.AddRoute(http.MethodGet, path, handleFunc)
}

func (h *HttpServer) Post(path string, handleFunc HandleFunc) { //addRoute 的衍生方法
	h.AddRoute(http.MethodGet, path, handleFunc)
}

func (h *HttpServer) Options(path string, handleFunc HandleFunc) { //addRoute 的衍生方法
	h.AddRoute(http.MethodGet, path, handleFunc)
}

func (h *HttpServer) Put(path string, handleFunc HandleFunc) { //addRoute 的衍生方法
	h.AddRoute(http.MethodGet, path, handleFunc)
}

// server 负责查找路由，并且执行命中的业务逻辑
func (h *HttpServer) server(ctx *Context) {
	//fmt.Println(i)
	_, err := ctx.Resp.Write([]byte("hello world"))
	if err != nil {
		return
	}
}
